(function(angular) {
	'use strict';
	angular.module('fs.waf').controller('cda.countryCalendar.updateController', updateController);
	updateController.$inject = [ '$scope', 'Constants', 'modalService', 'gridService', 'layoutConfig', 'validatorConfig', 'authService',
			'countryCalendarService', '$log' ];
	function updateController($scope, Constants, modalService, gridService, layoutConfig, validatorConfig, authService, countryCalendarService, $log) {
		var ctrl = this, countryCalendarInfo = $scope.$stateParams.params, errorMessage = {};
		ctrl.layoutConfig = layoutConfig;
		ctrl.validatorConfig = validatorConfig;
		ctrl.countryCalendar = {};
		var log = $log.getInstance('countryCalendar');
		
		$scope.$watch('updateCalendarYear', function(newValue, oldValue) {
			if (!newValue || newValue == '-1') {
				$scope.calendarYear = '';
				return;
			}
			countryCalendarInfo.calendarDay.year = newValue;
			authService.updateInit(countryCalendarInfo).then(function(response) {				
				ctrl.countryCalendar = response.data ;
				$scope.calendarYear = ctrl.countryCalendar.calendarDay.year;
			});
		});
		function diffArray(arr1, arr2) {
			if (arr1 == null) {
				return false;
			}
			if (arr1.length == 1 && arr2 == null) {
				return arr1[0];
			}
			for (var i = 0; i < arr1.length; i++) {
				var findFlag = false;
				for (var j = 0; j < arr2.length; j++) {
					if (arr1[i] == arr2[j]) {
						findFlag = true;
						break;
					}
				}
				if (!findFlag) {
					return arr1[i];
				}
			}
			return false;
		}
		
		function getDateIndex(date, arr) {
			for (var index = 0; index < arr.length; index++) {
				var eachDate = arr[index];
				if (eachDate.getYear() == date.getYear() && eachDate.getMonth() == date.getMonth() && eachDate.getDate() == date.getDate()) {
					return index;
				}
			}
			return -1;
		}
		$scope.$watch('vm.countryCalendar.weekendDays', function(newValue, oldValue) {
			if (ctrl.countryCalendar.calendarDay) {
				var daystrs;
				var calendarInfo = ctrl.countryCalendar.calendarDay.calendarInfo;
				if ((newValue != null && oldValue!= null && newValue.length > oldValue.length)
						|| (newValue != null && newValue.length == 1 && oldValue == null)) {
						var newWeekday = diffArray(newValue, oldValue);
						if (newWeekday == 'MON') {
							daystrs = calendarInfo[5 ].split(',');
						} else if (newWeekday == 'TUE') {
							daystrs = calendarInfo[7 ].split(',');
						} else if (newWeekday == 'WED') {
							daystrs = calendarInfo[9 ].split(',');
						} else if (newWeekday == 'THU') {
							daystrs = calendarInfo[11 ].split(',');
						} else if (newWeekday == 'FRI') {
							daystrs = calendarInfo[13 ].split(',');
						} else if (newWeekday == 'SAT') {
							daystrs = calendarInfo[1 ].split(',');
						} else if (newWeekday == 'SUN') {
							daystrs = calendarInfo[3 ].split(',');
						}
						for (var index in daystrs) {
							var date = new Date(Date.parse(daystrs[index].replace(/-/g,   "/")))
							if (getDateIndex(date, ctrl.countryCalendar.holidays) == -1) {
								ctrl.countryCalendar.holidays.push(date);
							}
							
							
						}
					} else {
						var rmvWeekday = diffArray(oldValue, newValue);
						if (rmvWeekday == 'MON') {
							daystrs = calendarInfo[5 ].split(',');
						} else if (rmvWeekday == 'TUE') {
							daystrs = calendarInfo[7 ].split(',');
						} else if (rmvWeekday == 'WED') {
							daystrs = calendarInfo[9 ].split(',');
						} else if (rmvWeekday == 'THU') {
							daystrs = calendarInfo[11 ].split(',');
						} else if (rmvWeekday == 'FRI') {
							daystrs = calendarInfo[13 ].split(',');
						} else if (rmvWeekday == 'SAT') {
							daystrs = calendarInfo[1 ].split(',');
						} else if (rmvWeekday == 'SUN') {
							daystrs = calendarInfo[3 ].split(',');
						}
						for (var index in daystrs) {
							var date = new Date(Date.parse(daystrs[index].replace(/-/g,   "/")))
							var index = getDateIndex(date, ctrl.countryCalendar.holidays);
							if (index > -1) {
								ctrl.countryCalendar.holidays.splice(index, 1);	
							}
						}
					}
				}
		}, true);
		
		
		ctrl.switchNewYearCalendar = function() {
			var calendarYear = $scope.calendarYear;
			if (!calendarYear) {
				var messages = [];
				messages.push("js.common.calendar.yearshouldbetween1990to2100");
				modalService.openErrorDialogs({
					'messages' : messages
				});
				return;
			}
			if (calendarYear < 1990 ) {
				var messages = [];
				messages.push("js.cda.calendar.yearcannotbeearlierthan1990");
				modalService.openErrorDialogs({
					'messages' : messages
				});
				return;
			}
			if (calendarYear > 2100 ) {
				var messages = [];
				messages.push("js.common.calendar.yearcannotbelaterthan2200");
				modalService.openErrorDialogs({
					'messages' : messages
				});
				return;
			}
			var hasCreated = false;
			if ($scope.yearList && $scope.yearList.length) {
				for (var i = 0; i < $scope.yearList.length; i++) {
					if ($scope.yearList[i].year == $scope.calendarYear) {
						hasCreated = true;
						$scope.updateCalendarYear = parseInt($scope.calendarYear);// can trigger
						break;
					}
				}
			}
			if (!hasCreated) {
				ctrl.countryCalendar.calendarDay.year = $scope.calendarYear;
				authService.createInit(ctrl.countryCalendar).then(function(response) {				
					ctrl.countryCalendar.calendarDay = response.data.calendarDay ;
					ctrl.countryCalendar.holidays = response.data.holidays;
					ctrl.countryCalendar.weekendDays = response.data.weekendDays;
					$scope.calendarYear = ctrl.countryCalendar.calendarDay.year;
					$scope.updateCalendarYear = '-1';
				});
			}
		};		
		
		ctrl.init = function() {
			countryCalendarService.initOptions($scope, ctrl).then(function() {
				authService.update(countryCalendarInfo).then(function(response) {
					ctrl.countryCalendar = response.data || countryCalendarInfo;
					$scope.calendarYear = ctrl.countryCalendar.calendarDay.year;
					$scope.updateCalendarYear = ctrl.countryCalendar.calendarDay.year;
					ctrl.countryCalendar.calendarDay.yearList = ctrl.countryCalendar.calendarDay.yearList ||[];
					if ( ctrl.countryCalendar.calendarDay.yearList.length == 0) {	
						ctrl.countryCalendar.calendarDay.yearList.push({year: ctrl.countryCalendar.calendarDay.year});
					}
					$scope.yearList = ctrl.countryCalendar.calendarDay.yearList;
					$scope.yearListChanged = [];
					if ($scope.yearList && $scope.yearList.length) {
						for (var i = 0; i < $scope.yearList.length; i++) {
							// $scope.yearList[i].year
							var data = {};
							data.value = $scope.yearList[i].year;
							data.label = $scope.yearList[i].year;
							$scope.yearListChanged.push(data);
						}
						var newYeayData = {'value':'-1','label':'New Year'};
						$scope.yearListChanged.push(newYeayData);
					}
				});
			});
		};

		ctrl.saveCurrency = function() {
			if (ctrl.countryCalendar.taskId) {
				return authService.updateContinueSave(ctrl.countryCalendar).then(saveSuccessful, saveFailed);
			} else {
				return authService.updateSave(ctrl.countryCalendar).then(saveSuccessful, saveFailed);
			}
		};

		ctrl.submitCurrency = function() {
			if (ctrl.countryCalendar.taskId) {
				return authService.updateContinueSubmit(ctrl.countryCalendar).then(submitSuccessful, submitFailed);
			} else {
				return authService.updateSubmit(ctrl.countryCalendar).then(submitSuccessful, submitFailed);
			}
		};

		function rowSelectionChanged(eventRow, selectedRows) {
			ctrl.selectedSubCommpanyList = selectedRows;
		}

		function submitSuccessful(response) {
			modalService.openAcknowledgeDialogs({
				'messages' : [ 'title.dialog.successful.submit' ],
				'btnCallback' : {
					'close' : function() {
						$scope.go('cda.countryCalendar.list');
					}
				},
				'redirections' : [ {
					'name' : 'title.infobar.workflow.list',
					'state' : 'cda.workflow.wfSetup.list',
					'params' : {}
				}, {
					'name' : 'title.infobar.countrycalendar.list',
					'state' : 'cda.countryCalendar.list',
					'params' : {}
				}]
			});
			
		}

		function submitFailed(response) {
			modalService.openErrorDialogs({
				'messages' : response.error
			});
		}

		function saveSuccessful(response) {
			modalService.openInfoDialogs({
				'messages' : [ 'title.dialog.successful.save' ]
			});
			if (response.data.task && response.data.task.taskId) {
				authService.saveSuccessfulProcess(response.data.task).then(function(response) {
					var routerInfo = response.data || {}, state = routerInfo.processState;
					delete routerInfo.processState;
					$scope.go(state, routerInfo);
				}, angular.noop);
			}
		}

		function saveFailed(response) {
			modalService.openErrorDialogs({
				'messages' : response.error
			});
		}
	}
})(angular);